<template>
  <a-modal class="common-modal" :title="title" :footer="null" :width="550" :visible="visible" :confirmLoading="confirmLoading" @cancel="handleCancel" :maskClosable="false" style="top:5%;">
    <a-spin :spinning="confirmLoading">
      <a-form :model="formState" @validateFields="handleOk" ref="formRef" layout="vertical" class="common-modal-content" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-row :gutter="24">
          <a-col :span="18">
            <a-form-item :label="$t('hangManage.stationRole')" name="role" :rules="editStationRule.role">
              <!-- <a-select v-model:value="formState.role" :placeholder="$t('common.pleaseSelect')" @change="onRoleChange"> -->
              <a-select v-model:value="formState.role" :placeholder="$t('common.pleaseSelect')">
                <a-select-option v-for="(item, index) in roleColorList" :key="index" :disabled="item.value == 1" :value="item.value">{{item.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row >
          <a-col :span="15">
            <!--            <a-form-item label="员工" name="staffId" :rules="editStationRule.staffNo">-->
            <a-form-item :label="$t('basicData.staff')" name="staffId">
              <a-select v-model:value="formState.staffId" allowClear :placeholder="$t('common.pleaseSelect')" :disabled="[1,4,6].includes(formState.role)" showSearch @change="onUserChange" :filter-option="filterOption">
                <a-select-option v-for="(item) in userList" :key="`${item.staffNo}${item.nickName}`" :value="item.id" :label="item.staffNo">
                  {{item.staffNo}} - {{item.nickName}}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="9" class="login-status-container" style="margin-top: 28px;text-align: center;">
            <span v-if="recordInfo.staffId"  >
              <span class="mr-8">{{ $t('other.logged') }}</span>
              <a-button type="warning" @click="staffLogout">{{ $t('other.logout') }}</a-button>
            </span>
            <span v-else>
              <span class="mr-8">{{ $t('other.notLog') }}</span>
              <a-button type="primary" :disabled="!formState.staffId || [1,4,6].includes(formState.role)" @click="staffLogin">{{ $t('other.login') }}</a-button>
            </span>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="18">
            <a-form-item :label="$t('hangManage.stationIn')" name="stationQty" :rules="editStationRule.stationQty">
              <a-input-number :placeholder="$t('common.pleaseInput')" v-model:value="formState.stationQty" :min="0" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="18">
            <a-form-item :label="$t('hangManage.capacity')" name="stationCapacity" :rules="editStationRule.stationCapacity">
              <a-input-number :placeholder="$t('common.pleaseInput')" v-model:value="formState.stationCapacity" :min="0" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="18">
            <a-form-item :label="$t('other.unloadSpeed')" name="autoOutClothSpeed" :rules="editStationRule.autoOutClothSpeed">
              <a-input-number :placeholder="$t('common.pleaseInput')" v-model:value="formState.autoOutClothSpeed" :min="0" />
            </a-form-item>
          </a-col>
          <a-col :span="6" class="login-status-container" style="line-height: 76px;">
            <span class="mr-8">{{ $t('other.spiece') }}</span>
          </a-col>
        </a-row>
      </a-form>
      <div class="common-modal-footer">
        <a-checkbox v-model:checked="allowUnfinishedHangerOut" class="cancel fl" v-if="formState.role == 2">{{ $t('other.allowUnfinishOut') }}</a-checkbox>
        <a-button @click="handleCancel" class="cancel">{{ $t('common.cancel') }}</a-button>
        <a-button @click="handleOk" type="primary" class="confirm">{{ $t('common.ok') }}</a-button>
      </div>
    </a-spin>
  </a-modal>
</template>
<script setup>
import { computed, nextTick, onMounted, ref } from 'vue'
import axios from '@/utils/request'
import { message } from 'ant-design-vue'
import { pick } from 'lodash'
const labelCol = { span: 23 }
const wrapperCol = { span: 23 }
// const labelCol = { xs: { span: 24 }, sm: { span: 4 } }
// const wrapperCol = { xs: { span: 24 }, sm: { span: 19 } }
import { editStationRule, roleColorList } from './prodTimeConfig'
import { store } from '@/store'
import i18n from '@/locales/index'

const { t } = i18n.global
let title = ref('')
let visible = ref(false)
let confirmLoading = ref(false)
let formState = ref({})
let formRef = ref()
let recordInfo = ref({})
let allowUnfinishedHangerOut = ref(false)
let emits = defineEmits(['ok'])
let userList = computed(() => {
  return store.state.normalData.employeesList
})
let staffNo = ref('')
const open = async (record) => {
  initModal(record)
  visible.value = true
  await nextTick()
  formRef.value.resetFields()
  // console.log(record)
  allowUnfinishedHangerOut.value = record.allowUnfinishedHangerOut ? true : false;
  formState.value = pick(recordInfo.value, ['role', 'stationQty', 'stationCapacity', 'stationId', 'staffId', 'autoOutClothSpeed'])
  if (record.staffId) onUserChange(record.staffId)
}
const initModal = (record) => {
  title.value = `${t('other.editStationMsg')}(${record.stationNo})`
  staffNo.value = ''
  recordInfo.value = { ...record }
  recordInfo.value.staffId = record.staffId == '0' ? null : record.staffId
}
// const onRoleChange = (value) => {
//   if (![1, 4, 6].includes(value)) {
//     formState.value.staffId = undefined
//     formState.value.staffName = null
//   }
// }
const onUserChange = (value) => {
  let selectInfo = userList.value.filter(i => i.id === value)
  // console.log( selectInfo,'-------------')
  if (!selectInfo.length) return
  formState.value.staffName = selectInfo[0].nickName
  staffNo.value = selectInfo[0].staffNo

}
const filterOption = (input, option) => {
  return option.key.toLowerCase().indexOf(input.toLowerCase()) >= 0
};
const getSendInfo = () => {
  // console.log( formState.value );
  // console.log( recordInfo.value);
  let url = '/api/hanger/hangerline-realtime/update-station-info'
  let { hangerLineNo, stationNo, stationId, hangerLineId, autoOutCloth } = recordInfo.value
  let { stationQty, role, stationCapacity, autoOutClothSpeed } = formState.value
  let params = {
    coathangerQuantity: stationQty,
    hangerLineId,
    line: hangerLineNo,
    role,
    station: stationNo,
    stationCapacity,
    autoOutCloth,
    stationId,
    autoOutClothSpeed,
    allowUnfinishedHangerOut: allowUnfinishedHangerOut.value ? 1 : 0
  }
  return { url, params }
}
const handleOk = async () => {
  try {
    await formRef.value.validateFields()
    if (formState.value.stationQty > formState.value.stationCapacity) {
      message.warning(t('other.siteNotOverCap'))
    } else {
      confirmLoading.value = true
      const info = getSendInfo()
      const res = await axios.postAction(info.url, info.params)
      if (res.success) {
        message.success(res.msg || t('common.doSuccess'))
        visible.value = false
        // outUnfinishedHanger.value = false
        emits('ok')
      }
      confirmLoading.value = false
    }
  } catch {
    confirmLoading.value = false
  }
}
const staffLogout = async () => {
  let { hangerLineNo, staffNo, stationNo } = recordInfo.value
  let params = {
    empId: staffNo,
    line: hangerLineNo,
    station: stationNo
  }
  const res = await axios.postAction('/api/hanger/hangerline-realtime/single-staff-offline', params)
  message[res.success ? 'success' : 'warning'](res.msg || (res.success ? t('common.doSuccess') : t('common.doError')))
}
const staffLogin = async () => {
  let { hangerLineNo, stationId, stationNo } = recordInfo.value
  let params = {
    hangerLineNo,
    staffId: formState.value.staffId,
    stationId,
    stationNo,
    staffName: formState.value.staffName,
    staffNo: staffNo.value
  }
  const res = await axios.postAction('/api/hanger/hangerline-realtime/single-staff-online', params)
  message[res.success ? 'success' : 'warning'](res.msg || (res.success ? t('common.doSuccess') : t('common.doError')))
}
const handleCancel = () => {
  formState.value = {}
  visible.value = false
}
/*const unbindHanger = async () => {
  // const res = false;
  if (confirm('确定要允许未完成衣架出站吗？')){
    // const params =  [];
    // const res = await axios.postAction('/api/hanger/hangerline-realtime/single-staff-online', params)
    // console.log(res)
    console.log('确定')
  }else{
    formState.value = {}
    visible.value = false
    console.log('不确定')
  }

}*/
defineExpose({
  open
})
onMounted(() => {
  store.dispatch('getEmpl')
})
</script>
